/**
 * Created by Administrator on 2015/12/22.
 */
var Promise = require('promise');
var logger = require('log4js').getLogger('activityService');
var comm = require('../../utils/commonUtils');
var memberDao = require('../dao/MemberDao')
var mailUtil = require('../../utils/mail');
var indexImgDao = require('../dao/IndexImgDao');
var loginService = {};

loginService.login = function(username,password){
    var params = {"username":username,"password":password};
    params.bak2 = 0;
    var orderby = "id";
    return new Promise(function(fulfill, reject){
        memberDao.getByParams(params,orderby).then(function(r){
            var result = null;
            if(r&& r.length>0){
                result = r[0];
            }
            fulfill(result)
        },function(err){
            reject(err)
        })
    })


}

loginService.register = function(username,password){
    var params = {"username":username,"password":password,"createTime":new Date()};
    params.headImgUrl = 'head.png';
    params.bak1 = 0;
    params.bak2 = 0;
    return memberDao.save(params,null);
}

loginService.registerThirdParty = function(username,openid,password){
    var params = {"username":username,"password":password,"createTime":new Date()};
    params.headImgUrl = 'head.png';
    params.bak1 = 0;
    params.bak2 = 1;
    params.bak5 = openid;
    return memberDao.save(params,null);
}

loginService.sendMail = function(mail){
    return new Promise(function(fulfil,reject){
        mailUtil.sendMail(mail,function(r){
            if(!r){
                reject(r);
            }else{
                fulfil(r);
            }
        });
    },function(err){

    })

}
loginService.getByUsername = function(username){
    var params = {};
    params.username = username;
    return memberDao.getByParams(params,'id');
}


loginService.getByOpenid = function(openid){
    var params = {};
    params.bak5 = openid;
    return memberDao.getByParams(params,'id');
}

loginService.getCover = function () {
    return indexImgDao.getByParams({},'id').then(function (img) {
        return Promise.resolve(img[0].imgUrl);
    })
}

module.exports = loginService;